package cn.com.tbshuda.shell.shell.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
/**
 * @ClassName ConnectShell
 * @Description 连接Shell脚本所在服务器
 * @Autor yanni
 * @Date 2020/3/30 16:52
 * @Version 1.0
 **/
public class ConnectShell {
    private Connection conn;
    private  Session session;
    private String ipAddr;
    private String userName;
    private String password;
    private String charset = Charset.defaultCharset().toString();
    private static final int TIME_OUT = 1000 * 5 * 60;
    public static Log log = LogFactory.getLog(ConnectShell.class);

    public ConnectShell(String ipAddr, String userName, String password, String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }

    public boolean login() throws IOException {
        conn = new Connection(ipAddr);
        conn.connect();

        return conn.authenticateWithPassword(userName, password); // 认证
    }
    public boolean openSession(){
        try {
                session = conn.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     *
     * @Title: excuteShellCommand
     * @Description: 执行shell脚本命令
     * @param shellpath
     * @return
     */
    public boolean excuteShellCommand(String shellpath) {
        InputStream in = null;
        boolean result = false;
        String str = "";
        try {
            session.execCommand(shellpath);
            in = new StreamGobbler(session.getStdout());
            str = this.processStdout(in, charset);
//            session.startShell();
            session.waitForCondition(ChannelCondition.STDOUT_DATA, TIME_OUT);

        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }
    public void close(){
        session.close();
        conn.close();

    }

    public String excuteShellCommand2(String shellpath) throws Exception {
        InputStream in = null;
        String result = "";
        try {
            if (this.login()) {
                Process exec = Runtime.getRuntime().exec(shellpath);// ipconfig
                in = exec.getInputStream();
                result = this.processStdout(in, this.charset);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }

    /**
     * 转化结果
     *
     * @param in
     * @param charset
     * @return
     * @throws UnsupportedEncodingException
     */
    public String processStdout(InputStream in, String charset) throws UnsupportedEncodingException {
        String line = null;
        BufferedReader brs = new BufferedReader(new InputStreamReader(in, charset));
        StringBuffer sb = new StringBuffer();
        try {
            while ((line = brs.readLine()) != null) {
                sb.append(line + "\n");
                System.out.println(line);
            }
        } catch (IOException e) {
            log.error("---转化出现异常---");
        }
        return sb.toString();
    }

}
